import axios from 'axios';
import * as constants from './constants';

const changeDetail = (data) => ({
  type: constants.GET_APPUSERDATA,
  appUserData: data,
});

// http://localhost:9080/users?start=0&length=10
export const getAppUserData = () => {
  return (dispatch) => {
    axios.get('http://localhost:9080/users?start=0&length=10',{
      headers: {
        'Authorization': "Bearer " + localStorage.getItem("access_token")
      }
    }).then((res) => {
      console.log(res.data.data);
      dispatch(changeDetail(res.data.data));
    }).catch(()=>{
      console.log('error');
    })
  }
}

// dialog open
export const onOpen = (record) => ({
  type: constants.OPEN_DIALOG,
  dialogVisible: true,
  dialogData: record
});

// dialog close
export const onClose = () => ({
  type: constants.CLOSE_DIALOG,
  dialogVisible: false
});

// search part
export const searchFormChange = (value) => ({
  type: constants.SEARCHFORM_CHANGE,
  searchId: value.id
});

export const searchUserById = (id) => {
  return (dispatch) => {
    axios.get('http://localhost:9080/users/'+id, {
      headers: {
        'Authorization': "Bearer " + localStorage.getItem("access_token")
      }
    }).then((res) => {
      if(res.data == '') {
        alert("未搜索到结果");
      }else {
        console.log(res.data);
        let newData = [];
        newData.push(res.data);
        dispatch(changeDetail(newData));
      }
    }).catch(() => {
      console.log('error');
    })
  }
};

// enabled part
export const changeEnabled = (checked, id) => {
  let checkedNum = checked ? 1 : 0;
  return () => {
    axios.post('http://localhost:9080/users/'+id+'/'+checkedNum, {
      headers: {
        'Authorization': "Bearer " + localStorage.getItem("access_token")
      }
    }).then((res) => {
      alert('设置成功！');
    }).catch(() => {
      alert('error');
    })
  }
};